<?php

class stPostcardUser_model extends stmodel_2_1 {

    public function __construct($config) {
        parent::__construct($config);
        $this->setTableName($this->prefix . 'st_postcard_user');
        $this->setPrimaryKey('id');
        $fucntionName = $this->config['plugin_name'] . "Functions";
        $this->functions = new $fucntionName($this->config);
    }

    public function saveStPostcardUser($data, $form_flash = 0) {
        if (empty($data['cdate'])) {
            $data['cdate'] = date('Y-m-d H:i:s');
        }
        if (!$form_flash) {
            if (empty($data['id'])) {
                $data['password'] = md5($data['password']);
            } else {
                if (!empty($data['password']))
                    $data['password'] = md5($data['password']);
                else
                    unset($data['password']);
            }
        }
        if (($this->checkEmail($data['email'], $data['smt_user_id']) && !empty($data['fb_user_id'])) || (!$this->checkEmail($data['email']) || !empty($data['id']))) {
            $data['id'] = $this->checkEmail($data['email'], $data['smt_user_id']);
            if ($this->saveRecords($data)) {
                return $this->getLastId();
            } else {
                return false;
            }
        }
    }

    public function countRecords($args = '') {

        $result = $this->getRecords($args);
        return count($result);
    }

    public function getLastId() {
        $query = "SELECT max(id)
        FROM $this->_tableName
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function checkLogin($email, $password, $smt_user_id) {
        $query = "SELECT * 
        FROM $this->_tableName 
        WHERE password like('{$password}') 
        AND email like('{$email}') 
        AND smt_user_id = {$smt_user_id} 
        ";
//        echo $query;
        $result = $this->get_results($query);
        return $result[0];
    }

    public function checkEmail($email, $smt_user_id = '') {
        $query = "SELECT id
        FROM $this->_tableName
        WHERE email like('{$email}')
        AND smt_user_id = {$smt_user_id}
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function checkFBLogin($fb_user_id, $smt_user_id) {
        $query = "SELECT * 
        FROM $this->_tableName 
        WHERE fb_user_id like('{$fb_user_id}')
        AND smt_user_id = {$smt_user_id}
        ";
        $result = $this->get_row($query);
        return $result;
    }

    public function getRecords($args = '', $output = false) {
        $default_args = array(
            'fields' => '*',
            'and_where' => '',
            'or_where' => '',
            'where' => '',
            'order' => '',
            'limit' => '',
            'group_by' => '',
            'custom_query' => '',
        );
        if ($args == '')
            $args = $default_args;

        $fields = $args['fields'] ? $args['fields'] : '*';
        $and_where = $args['and_where'] ? $args['and_where'] : '';
        $or_where = $args['or_where'] ? $args['or_where'] : '';
        $custom_where = $args['where'] ? $args['where'] : '';
        $order = $args['order'] ? $args['order'] : '';
        $limit = $args['limit'] ? $args['limit'] : '';
        $group_by = $args['group_by'] ? $args['group_by'] : '';
        $custom_query = $args['custom_query'] ? $args['custom_query'] : '';
        if (!empty($custom_query)) {
            $query = $custom_query;
        } else {
            if ($fields != '*')
                $fields = implode(', ', $fields);
            //
            $where = ' WHERE ';

            if ($and_where != '')
                $where .= implode('', $and_where);
            if ($or_where != '')
                $where .= implode('', $or_where);
            if ($custom_where != '')
                $where .= $custom_where;
            if ($where == ' WHERE ')
                $where = '';
            //
            if ($order != '')
                $order = ' ORDER BY ' . implode(' ', $order);
            //
            if ($limit != '')
                $limit = ' LIMIT ' . implode(', ', $limit);
            if ($group_by != '')
                $group_by = ' GROUP BY ' . $group_by;
            $card_table = $this->prefix . 'st_postcard_card';
            $card_share_table = $this->prefix . 'st_postcard_share';

            $query = "SELECT $fields
            FROM wp_st_postcard_user user 
            LEFT JOIN
            (
            SELECT user_id, count(card.id) created 
            FROM wp_st_postcard_card card 
            $where
            AND `folder_name` like('{$this->config['folder_generated']}')
            GROUP BY user_id) table3 ON table3.user_id = user.id
            LEFT JOIN
            (
            SELECT card.id id,card.user_id user_id, sum(share.number_share) shared_email 
            FROM wp_st_postcard_card card 
            LEFT JOIN wp_st_postcard_share `share` on share.card_id = card.id 
            WHERE `type_share` like('email') GROUP BY card.user_id 
            ) table1 ON table1.user_id = user.id 
            LEFT JOIN
            (
            SELECT card.id id,card.user_id user_id, sum(share.number_share) shared_fb 
            FROM wp_st_postcard_card card 
            LEFT JOIN wp_st_postcard_share `share` on share.card_id = card.id 
            WHERE `type_share` like('facebook') GROUP BY card.user_id
            ) table2 ON table2.user_id = user.id 
            $where
            $group_by
            $order
            $limit
            ";
        }
//        echo $query;
        if($output == ARRAY_A){
            return $this->get_results($query, ARRAY_A);
        }else{
            return $this->get_results($query);
        }
        
    }

    public function exportCSV() {
        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        //user.*, table1.id card_id, sum(table1.shared_email) shared_email, sum(table2.shared_fb) shared_fb
        $args['fields'] = array('user.name name, user.email email, table3.created created, (COALESCE(shared_email,0)+COALESCE(shared_fb,0)) shared, sum(table2.shared_fb) shared_fb, sum(table1.shared_email) shared_email,user.cdate create_date ');
        $args['limit'] = array();
        $smt_user_id = $this->functions->getCurrentSmtUserID($this->config);
        $args['where'] = " smt_user_id = $smt_user_id";

        $args['group_by'] = 'user.id';
        $results = $this->getRecords($args, ARRAY_A);
        $html = '';
        $keys = array_keys($results[0]);
        $columns = implode(';', $keys). "\n";        
        foreach ($results as $value) {
            $html .= implode(';', $value) . "\n";
        }
        // xuan phuc support 04-08-2011
        echo chr(255).chr(254).mb_convert_encoding($columns . $html, "UTF-16LE", "UTF-8");
        return true;
    }

}